package com.xy.thirdpart.deepseek;

import io.github.pigmesh.ai.deepseek.core.DeepSeekClient;
import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionModel;
import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionRequest;
import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionResponse;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@Component
public class DeepSeekProcessor {
    // 共享的 DeepSeekClient 实例（线程安全，可复用）
    private final DeepSeekClient deepSeekClient = DeepSeekClient.builder()
            .baseUrl("https://api.deepseek.com")
            .openAiApiKey("sk-150946953bc344e489033b3429f260c1")
            .build();
    // 固定大小线程池
    private final ExecutorService executor = Executors.newFixedThreadPool(10);

    /**
     * 处理单个问题并返回答案字符串，出现异常时返回默认提示。
     */
    public String processQuestion(String context, String question) {
        try {
            ChatCompletionRequest request = ChatCompletionRequest.builder()
                    .model(ChatCompletionModel.DEEPSEEK_REASONER)
                    .addSystemMessage("你是一个专业的问答助手，请根据上下文回答问题。" + context )
                    .addUserMessage(question+",以josn形式返回,如果没有答案就回复无")
                    .temperature(0.3)
                    .build();
            // 使用复用的 DeepSeekClient 实例
            ChatCompletionResponse response = deepSeekClient
                    .chatCompletion(request)
                    .execute();
                System.out.println("|||" + question + ": " +response.content()+"|||");
            return response.content();
        } catch (Exception e) {
            // 异常时返回默认提示，并可记录日志
            return "对不起，当前无法回答此问题。";
        }
    }

    /**
     * 并发批量处理问题，返回所有回答的集合。
     */
    @Async
    public CompletableFuture<Set<String>> batchProcess(String context, Set<String> questions) {
        // 为每个问题创建异步任务，使用 supplyAsync 返回答案字符串
        List<CompletableFuture<String>> futures = questions.stream()
                .map(question -> CompletableFuture.supplyAsync(
                        () -> processQuestion(context, question), executor))
                .toList();

        // 等待所有任务完成，然后收集结果到 Set<String>
        return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
                .thenApply(v -> futures.stream()
                        .map(CompletableFuture::join)  // 获取每个任务的返回值
                        .collect(Collectors.toSet()));
    }

/*
    public static void main(String[] args) {
        // 线程安全的存储结构

        ConcurrentMap<String, String> resultMap = new ConcurrentHashMap<>();

        // 初始化 DeepSeekClient
        DeepSeekClient client = DeepSeekClient.builder()
                .baseUrl("https://api.deepseek.com")
                .openAiApiKey("sk-150946953bc344e489033b3429f260c1")
                .build();

        // 创建请求
        ChatCompletionRequest request = ChatCompletionRequest.builder()
                .model(ChatCompletionModel.DEEPSEEK_REASONER)
                .addSystemMessage("你是一个专业的问答助手，请根据上下文回答问题。原告的姓名是李四") // 注入上下文
                .addUserMessage("原告的姓名是什么,以josn形式返回，键为ygxm")
                .temperature(0.3)
                .build();
        SyncOrAsyncOrStreaming<ChatCompletionResponse> response = client.chatCompletion(request);
        ChatCompletionResponse syncResponse = response.execute();
       // resultMap.put("a",syncResponse.content());
        System.out.println(syncResponse.content());
    }*/
}
